package com.app.configuration.web.session;


import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;

import com.app.util.common.Constants;

@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener {

    public Logger logger = Logger.getLogger(this.getClass());

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        
        @SuppressWarnings("unused")
        HttpSession session = httpSessionBindingEvent.getSession();
        logger.debug("--session添加属性："+httpSessionBindingEvent.getName()+"："+httpSessionBindingEvent.getValue());
        
        //当session添加用户属性的时候，则记录这个用户为在线用户
        if(httpSessionBindingEvent.getName().equals(Constants.SESSION_USER)) {
        	SessionContext.addSession(session);
        }
        
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        logger.debug("--attributeRemoved--");
        
        //当session添加用户属性的时候，则移除这个用户为在线用户
        if(httpSessionBindingEvent.getName().equals(Constants.SESSION_USER)) {
        	SessionContext.delSession(httpSessionBindingEvent.getSession());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
        
    }

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        
        HttpSession session = event.getSession();        
        logger.debug("---session创建----"+session.getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) throws ClassCastException {
        
        HttpSession session = event.getSession();
        if(session.getAttribute(Constants.SESSION_USER) != null) {
        	SessionContext.delSession(session);
        }
        
        logger.debug("---session删除----"+session.getId());
    }

}
